package src.main.java.com.pms.gui.dialog.user;

import src.main.java.com.pms.service.UserService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ChangeUsernameDialog extends JDialog {
    private JTextField oldUsernameField;
    private JTextField newUsernameField;
    private UserService userService;

    public ChangeUsernameDialog(JFrame parent) {
        super(parent, "修改用户名", true);
        userService = new UserService();
        initComponents();
    }

    private void initComponents() {
        setSize(350, 200);
        setLocationRelativeTo(getParent());

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);

        // 旧用户名
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(new JLabel("旧用户名:"), gbc);

        gbc.gridx = 1;
        oldUsernameField = new JTextField(20);
        panel.add(oldUsernameField, gbc);

        // 新用户名
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(new JLabel("新用户名:"), gbc);

        gbc.gridx = 1;
        newUsernameField = new JTextField(20);
        panel.add(newUsernameField, gbc);

        // 按钮
        JButton changeButton = new JButton("修改");
        changeButton.addActionListener(new ChangeUsernameActionListener());

        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        panel.add(changeButton, gbc);

        add(panel);
        setVisible(true);
    }

    private class ChangeUsernameActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String oldUsername = oldUsernameField.getText();
            String newUsername = newUsernameField.getText();

            if (oldUsername == null || oldUsername.trim().isEmpty() || newUsername == null || newUsername.trim().isEmpty()) {
                JOptionPane.showMessageDialog(ChangeUsernameDialog.this, "用户名不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            try {
                if (userService.changeUsername(oldUsername, newUsername)) {
                    JOptionPane.showMessageDialog(ChangeUsernameDialog.this, "用户名修改成功！");
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(ChangeUsernameDialog.this, "用户名修改失败，新用户名可能已存在！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(ChangeUsernameDialog.this, "用户名修改失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}
